package com.chenfwind.controller;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.chenfwind.common.Constant;
import com.chenfwind.common.ResultVO;
import com.chenfwind.common.StringUtils;
import com.chenfwind.domain.User;
import com.chenfwind.domain.User1;
import com.chenfwind.domain.UserTrack;
import com.chenfwind.domain.vo.UserLoginVO;
import com.chenfwind.domain.vo.UserTrackVO;
import com.chenfwind.domain.vo.UserVO;
import com.chenfwind.service.UserService;
import com.chenfwind.service.UserTrackService;
import com.chenfwind.shiro.Realm;
import com.chenfwind.utils.BeanUtils;

import sun.net.util.IPAddressUtil;

import com.chenfwind.service.User1Service;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private User1Service user1Service;

	@Autowired
	private UserService userService;
	
	@Autowired
	private UserTrackService userTrackService;

	@RequestMapping("/showUser")
	public String showUser(HttpServletRequest request, Model model) {
		int userId = Integer.parseInt(request.getParameter("id"));
		User1 user = this.user1Service.getUserById(userId);
		model.addAttribute("user", user);
		System.out.println(user.getUserName());
		return "showUser";
	}

//	@ResponseBody
//	@RequestMapping("/loginWeb")
//	public ResultVO<UserLoginVO> loginWeb(HttpSession session,
//			@RequestParam(value = "account", required = false) String account,
//			@RequestParam(value = "password", required = false) String password) {
//		ResultVO<UserLoginVO> vo = ResultVO.create();
//		User user = (User) userService.getUserByAccount(account);
//		
//		//登录后存放进shiro token
//		UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(),user.getPassword());
//		Subject subject = SecurityUtils.getSubject();
//		subject.login(token);
//		System.out.println("登录成功");
//		return vo;
//	}

	/*****
	 * 登录
	 * 
	 * @param session
	 * @param account
	 * @param password
	 * @param errors
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/login" , method = RequestMethod.POST )
	public ResultVO<UserLoginVO> login(HttpSession session,
			@RequestParam(value = "account", required = false) String account,
			@RequestParam(value = "password", required = false) String password) {
		ResultVO<UserLoginVO> vo = ResultVO.create();
		try {
			if (account == null || password == null) {
				return ResultVO.create(Constant.CODE_NOPARAM, Constant.CODE_MSG_NOPARAM);
			}
			User inputUser = new User();
			inputUser.setAccount(account);
			inputUser.setPassword(password);

			User checkUser = userService.getUserByAccount(inputUser.getAccount());
			if (checkUser == null) {
				return ResultVO.create(Constant.CODE_ACCOUNT_NOFOUND, Constant.CODE_MSG_ACCOUNT_NOFOUND);
			}

			User loginUser = userService.getUserByAccountAndPassword(inputUser.getAccount(), inputUser.getPassword());
			if (loginUser == null || !loginUser.getPassword().equals(inputUser.getPassword())) {
				return ResultVO.create(Constant.CODE_ACCOUNT_PWD_INVALID, Constant.CODE_MSG_ACCOUNT_PWD_INVALID);
			} else if (loginUser.getStatus() == Constant.STATUS_OFF) {
				return ResultVO.create(Constant.STATUS_OFF, Constant.CODE_MSG_STATUS_OFF);
			} else {
				
//				UsernamePasswordToken token = new UsernamePasswordToken(checkUser.getAccount(),checkUser.getPassword());
//				Subject subject = SecurityUtils.getSubject();
//				subject.login(token);
				session.setAttribute("user", loginUser);
				// token
				// 更新用户最后访问时间
				UserVO userVO = new UserVO();
				userVO.setId(loginUser.getId());
				userVO.setAccessTime(new Date());
				// modifyUserInfo

				UserLoginVO userLoginVO = new UserLoginVO();
				com.chenfwind.utils.BeanUtils.copyProperties(loginUser, userLoginVO);
				vo.setResult(userLoginVO);
				vo.reCalcStatus();
				System.out.println(vo);
				return vo;
			}
		} catch (Exception e) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return ResultVO.create(Constant.CODE_ERROR, sw.toString());
		}
	}

	@ResponseBody
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ResultVO<UserLoginVO> register(HttpSession session,
			@RequestParam(value = "userInfoJson", required = false) String userInfoJson) throws Exception {
		ResultVO<UserLoginVO> vo = ResultVO.create();
		UserVO userInfo = JSON.parseObject(userInfoJson, UserVO.class);
		if (userInfo == null || userInfo.getAccount() == null) {
			return ResultVO.create(Constant.CODE_NOPARAM, Constant.CODE_MSG_NOPARAM);
		}
		User checkUser = userService.getUserByAccount(userInfo.getAccount());
		if (checkUser != null) { // 检查账号是否已存在
			return ResultVO.create(Constant.CODE_ACCOUNT_EXISTS, Constant.CODE_MSG_ACCOUNT_EXISTS);
		}

		User user = UserVO2User(userInfo, null);
		String ID = StringUtils.genUUID();
		user.setId(ID);
		// 状态默认为“启动”
		user.setStatus(1);
		userService.register(user);
		UserTrack userTrack = UserTrackVO2UserTrack(userInfo,ID);
		userTrackService.insertUserTrack(userTrack);
		
		return ResultVO.create(Constant.CODE_SUCCESS);
	}

	@ResponseBody
	@RequestMapping(value = "/getUserInfo" , method = RequestMethod.POST)
	public ResultVO<UserVO> getUserInfo(HttpSession session , @RequestParam(value = "userId" , required = false) String userId){
		ResultVO<UserVO> vo = ResultVO.create();
		if( userId  == null ){
			return ResultVO.create(Constant.CODE_NOPARAM , Constant.CODE_MSG_NOPARAM);
		}
		User user = userService.findUserById(userId);
		if (user == null) {
			return ResultVO.create(Constant.CODE_ERROR,"找不到ID为" + userId + "的用户信息");
		} else {
			UserTrack userTrack = userTrackService.getTrackByUserIDAndStatus(userId);
			UserVO userVO = new UserVO();
			BeanUtils.copyProperties(user, userVO);
			user2UserVO(user,userVO);
			/*坐标*/
			userVO.setX(userTrack.getX().toString());
			userVO.setY(userTrack.getY().toString());
			userVO.setTrackName(userTrack.getTrackname());
			userVO.setTrackID(userTrack.getId());
			
			userVO.setAccessTime(null);
			userVO.setPassword(null);
			userVO.setStatus(null);
			userVO.setRegisterTime(null);
			userVO.setX(userTrack.getX()+"");
			userVO.setY(userTrack.getY()+"");
			userVO.setTrackName(userTrack.getTrackname());
			vo.setResult(userVO);
			vo.reCalcStatus();
		}
		return vo;
	}
	
	public UserTrack UserTrackVO2UserTrack(UserVO userInfo,String ID){
		UserTrack userTrack = new UserTrack();
		userTrack.setUserId(ID);
		userTrack.setX(Double.valueOf(userInfo.getX()));
		userTrack.setY(Double.valueOf(userInfo.getY()));
		userTrack.setTrackname(userInfo.getTrackName());
		userTrack.setId(StringUtils.genUUID());
		userTrack.setRank(1);
		userTrack.setStatus(1);
		return userTrack;
	}
	
	/*
	 * UserVO 转换成User持久化类
	 */
	public User UserVO2User(UserVO userInfo, User user) throws Exception {
		if (user == null) {
			user = new User();
			user.setRegisterTime(new Date());
		}
		
		// 自己写的util类只拷贝非null属性
		com.chenfwind.utils.BeanUtils.copyProperties(userInfo, user);
		if (userInfo.getGender() != null){
			user.setGender(Integer.parseInt(userInfo.getGender()));
		}
		// // 省 Id
		// if (userInfo.getProvinceId() != null) {
		// user.setRegionByProvinceId(regionService.getRegionById(userInfo.getProvinceId()));
		// }
		// // 市ID
		// if (userInfo.getCityId() != null) {
		// user.setRegionByCityId(regionService.getRegionById(userInfo.getCityId()));
		// }
		// // 县区ID
		// if (userInfo.getCountyId() != null) {
		// user.setRegionByCountyId(regionService.getRegionById(userInfo.getCountyId()));
		// }

		return user;
	}
	
	public void user2UserVO(User user , UserVO userVO){
		
		if (user.getGender() != null) {
			userVO.setGender(user.getGender().toString());
		}
	}

	
	@ResponseBody
	@RequestMapping(value = "/modifyUserInfo", method = RequestMethod.POST)
	public ResultVO<String> modifyUserInfo(HttpSession session, @RequestParam(value = "userInfoJson", required = false) String userInfoJson) throws Exception{
		UserVO  userInfo = JSON.parseObject(userInfoJson,UserVO.class);
		
		if (userInfo == null ) {
			return ResultVO.create(Constant.CODE_NOPARAM,Constant.CODE_MSG_ACCOUNT_NOFOUND);
		}
		System.out.println(userInfo.getId());
		
		User checkUser = userService.findUserById(userInfo.getId());
		if (checkUser == null) {
			return ResultVO.create(Constant.CODE_ACCOUNT_EXISTS , Constant.CODE_MSG_ACCOUNT_NOFOUND);
		}
		User user = UserVO2User(userInfo,checkUser);
//		if (!checkUser.getAccount().equals(user.getAccount())) {
//			checkUser = userService.getUserByAccount(userInfo.getAccount());
//			if (checkUser != null) {
//				return ResultVO.create(Constant.CODE_ACCOUNT_EXISTS,Constant.CODE_MSG_ACCOUNT_NOFOUND);
//			}
//		}
		
		int registerUser = userService.modifyUserInfo(user,userInfo);
		
		System.out.println(registerUser);
		return ResultVO.create(Constant.CODE_SUCCESS);
	}
	
	@ResponseBody
	@RequestMapping(value = "/getUserTrack", method = RequestMethod.POST)
	public ResultVO<List<UserTrack>> getUserTrack(HttpSession session,@RequestParam(value = "userId" ,required = false) String userId ){
		ResultVO<List<UserTrack>> vo= ResultVO.create();
		User checkUser = userService.findUserById(userId);
		if (checkUser == null) {
			return ResultVO.create(Constant.CODE_ACCOUNT_EXISTS , Constant.CODE_MSG_ACCOUNT_NOFOUND);
		}
		List<UserTrack> userTrackList = userTrackService.getTrackByUserID(userId);
		if (userTrackList == null) {
			return ResultVO.create(Constant.CODE_NODATA , Constant.CODE_NO_DATA);
		} 
		
		vo.setResult(userTrackList);
		vo.setStatus(Constant.CODE_SUCCESS);
		return vo;
	}
	/* 
	 * 测试时写的
	 */
	@ResponseBody
	@RequestMapping(value = "/test", method = RequestMethod.POST)
	public List<UserVO> test() {
		List<UserVO> aa = new ArrayList<UserVO>();
		UserVO userVO = new UserVO();
		userVO.setAccount("hahahha");
		userVO.setId("dddd");
		aa.add(userVO);
		UserVO userVO1 = new UserVO();
		userVO1.setAccount("hahahha");
		userVO1.setId("dddd");
		aa.add(userVO1);
		return aa;
	}
	
	@ResponseBody
	@RequestMapping(value = "/json" , method = RequestMethod.POST)
	public ResultVO<List<UserVO>> testJson(){
		ResultVO<List<UserVO>> vo = ResultVO.create();
		List<UserVO> aa = new ArrayList<UserVO>();
		UserVO userVO = new UserVO();
		userVO.setAccount("hahahha");
		userVO.setId("dddd");
		aa.add(userVO);
		UserVO userVO1 = new UserVO();
		userVO1.setAccount("hahahha");
		userVO1.setId("dddd");
		aa.add(userVO1);
		vo.setRows(aa);
		vo.setTotal(7);
		return vo;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getUserList", method = RequestMethod.POST)
	public ResultVO<List<UserVO>> getUserList(HttpSession session ){
		ResultVO<List<UserVO>> vo= ResultVO.create();
		List<User> userList = userService.getAllUser();
		List<UserVO> userVOList = new ArrayList<UserVO>();
		UserVO userVO = null;
		for (User user :userList) {
			if (!"1".equals(user.getId()) && !"2".equals(user.getId())){
				userVO = User2UserVO1(user,null);
				userVOList.add(userVO);
			}
			
		}
		
		vo.setTotal(userVOList.size());
		vo.setRows(userVOList);
		return vo;
	}
	
	
	
	public UserVO User2UserVO1(User user, UserVO userVO){
		if (userVO == null){
			userVO = new UserVO();
			UserTrack userTrack = userTrackService.getTrackByUserIDAndStatus(user.getId());
			userVO.setX(userTrack.getX().toString());
			userVO.setY(userTrack.getY().toString());
			userVO.setTrackName(userTrack.getTrackname());
		}
		com.chenfwind.utils.BeanUtils.copyProperties(user, userVO);
		return userVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/delUpdate", method = RequestMethod.POST)
	public ResultVO<List<UserVO>> delUpdate(HttpSession session,@RequestParam(value = "userId" ,required = false) String userId ){
		ResultVO<List<UserVO>> vo= ResultVO.create();
		if (userId == null) {
			return ResultVO.create(Constant.CODE_NOPARAM,Constant.CODE_MSG_ACCOUNT_NOFOUND);
		}
		userService.delUser(userId);
		
		List<User> userList = userService.getAllUser();
		List<UserVO> userVOList = new ArrayList<UserVO>();
		UserVO userVO = null;
		for (User user :userList) {
			if (!"1".equals(user.getId()) && !"2".equals(user.getId())){
				userVO = User2UserVO1(user,null);
				userVOList.add(userVO);
			}
		}
		
		vo.setTotal(userVOList.size());
		vo.setRows(userVOList);
		return vo;
	}
}
